package controller

import (
	"example.com/m/model"
	"example.com/m/repository"
	"example.com/m/response"
	"example.com/m/vo"
	"github.com/gin-gonic/gin"
	"strconv"
)

type IcategoryController interface {
	RestController
}

type CategoryController struct {
	Respository repository.CategoryRepository
}

func NewCateGoryController() IcategoryController {
	//取数据库连接池
	repository := repository.NewCategoryRepository()
	//添加自动迁移
	repository.DB.AutoMigrate(model.Category{})
	return CategoryController{Respository: repository}
}

func (c CategoryController) Create(ctx *gin.Context) {

	var requestCategory vo.CreateCatgoryRequest
	if err := ctx.ShouldBind(&requestCategory); err != nil {
		response.Fail(ctx, "数据验证错误，分类名称必填", nil)
		return
	}
	//否则的话创建这个分类
	category, err := c.Respository.Create(requestCategory.Name)
	if err != nil {
		//返回数据验证错误
		response.Fail(ctx, "创建失败", nil)
		return
	}

	response.Success(ctx, gin.H{"category": category}, "")
}

func (c CategoryController) Update(ctx *gin.Context) {
	//绑定body中的参数
	var requestCategory model.Category
	ctx.Bind(&requestCategory)
	if requestCategory.Name == "" {
		//返回数据验证错误
		response.Fail(ctx, "数据验证错误，分类名称必填", nil)
		return
	}
	//绑定path中的参数，将获取到的字符串强转成int类型的
	categoryId, _ := strconv.Atoi(ctx.Params.ByName("id"))
	//查询categoryId是否存在
	var Updatecategory model.Category
	if c.Respository.DB.Find(&Updatecategory, categoryId).RecordNotFound() {
		response.Fail(ctx, "分类不存在", nil)
		return
	}
	//更新分类
	c.Respository.DB.Model(&Updatecategory).Update("name", requestCategory.Name)
	response.Success(ctx, gin.H{"category": Updatecategory}, "修改成功")
}

func (c CategoryController) Show(ctx *gin.Context) {
	categoryId, _ := strconv.Atoi(ctx.Params.ByName("id"))
	//查询categoryId是否存在
	var category model.Category
	if err := c.Respository.DB.Delete(model.Category{}, categoryId); err != nil {
		response.Fail(ctx, "分类不存在", nil)
		return
	}
	response.Success(ctx, gin.H{"category": category}, "修改成功")
}

func (c CategoryController) Delete(ctx *gin.Context) {
	//绑定path中的参数，将获取到的字符串强转成int类型的
	categoryId, _ := strconv.Atoi(ctx.Params.ByName("id"))
	if err := c.Respository.DB.Delete(model.Category{}, categoryId).Error; err != nil {
		response.Fail(ctx, "删除失败，请重试", nil)
		return
	}
	response.Success(ctx, nil, "")
}
